<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>vue</title>
  </head>
  <body>
  <script src="https://unpkg.com/vue@2.6.14/dist/vue.js"></script>
    <div id="app">
     <div  v-draggable:absolute.disable="{width:'100px',height:'100px',backgroundColor:'green'}"></div>
    </div>
    <script>
        //定义一个指令 名字叫draggable,再定义一个对象，里面编写很多钩子函数
        Vue.directive('draggable',{
            //这就是一个钩子函数，你不需要自己调用此函数，只需要写好放在这就可以
            bind(el,binding){
                console.log(binding)
                if(binding.modifiers.disable)return;
                //获取指令的值{width:'100px',height:'100px',backgroundColor:'green'}
                let {value} = binding;
                //循环此对象，把里面的属性赋给真实DOM的样式对象
                for(let key in value){
                    el.style[key]=value[key];
                }
                el.style.position = binding.arg;
                let isDragging = false;//当前是否正在拖拽
                let offsetX,offsetY;
                //给当前这个DIV添加鼠标按下的事件
                el.addEventListener('mousedown',(event)=>{
                    offsetX=event.offsetX;
                    offsetY=event.offsetY;
                    isDragging=true;
                });
                //当我们移动鼠标的时候，计算元素的最新的位置 
                el.addEventListener('mousemove',(event)=>{
                   if(isDragging){
                    el.style.left = event.clientX-offsetX +'px';
                    el.style.top = event.clientY-offsetY+'px';
                   }
                });
                //当松下的时候，停止拖动
                el.addEventListener('mouseup',(event)=>{
                    isDragging=false;
                });
            }
        });
        var vm = new Vue({
            el:'#app'
        })
    </script>
  </body>
</html>
